home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1998 January: Mac OS SDK / Dev.CD Jan 98 SDK1.toast / Development Kits (Disc 1) / Apple Shared Library Manager / ASLM Examples / Sample Apps / CSample / Sources / Sample.c next >
Encoding:
C/C++ Source or Header  |  1996-11-19  |  27.6 KB  |  813 lines  |  [TEXT/MPS ]

  1. /*
  2.     File:        Sample.c
  3.  
  4.     Contains:    This is a simple application, based on the DTS traffic light example,
  5.                 that demonstrates how to use the Shared Library Manager. It puts the
  6.                 functionality of the traffic light window into a shared library and
  7.                 then uses that library from the client application.
  8.  
  9.     Copyright:    © 1993-1994 by Apple Computer, Inc., all rights reserved.
  10.  
  11. */
  12.  
  13. #include <LibraryManager.h>
  14. #include <LibraryManagerUtilities.h>
  15.  
  16. #include <limits.h>
  17. #include <Types.h>
  18. #include <Resources.h>
  19. #include <QuickDraw.h>
  20. #include <Fonts.h>
  21. #include <Events.h>
  22. #include <Windows.h>
  23. #include <Menus.h>
  24. #include <TextEdit.h>
  25. #include <Dialogs.h>
  26. #include <Desk.h>
  27. #include <ToolUtils.h>
  28. #include <Memory.h>
  29. #include <SegLoad.h>
  30. #include <Files.h>
  31. #include <OSUtils.h>
  32. #include <OSEvents.h>
  33. #include <DiskInit.h>
  34. #include <Packages.h>
  35. #include <Traps.h>
  36.  
  37. #include "Sample.h"
  38. #include "SampleLibrary.h"
  39.  
  40. /* The "g" prefix is used to emphasize that a variable is global. */
  41.  
  42. /* gMac is used to hold the result of a SysEnvirons call. This makes
  43.    it convenient for any routine to check the environment. */
  44.  
  45. SysEnvRec    gMac;                /* set up by Initialize */
  46.  
  47. /* gHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  48.    trap is available. If it is false, we know that we must call GetNextEvent. */
  49.  
  50. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  51.  
  52. /* gInBackground is maintained by our osEvent handling routines. Any part of
  53.    the program can check it to find out if it is currently in the background. */
  54.  
  55. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  56.  
  57. /* Here are declarations for all of the C routines. In MPW 3.0 and later we can use
  58.    actual prototypes for parameter type checking. */
  59.  
  60. void EventLoop( void );
  61. void DoEvent( EventRecord *event );
  62. void AdjustCursor( Point mouse, RgnHandle region );
  63. void GetGlobalMouse( Point *mouse );
  64. void DoUpdate( WindowPtr window );
  65. void DoActivate( WindowPtr window, Boolean becomingActive );
  66. void DoContentClick( WindowPtr window );
  67. void DrawWindow( WindowPtr window );
  68. void AdjustMenus( void );
  69. void DoMenuCommand( long menuResult );
  70. Boolean DoCloseWindow( WindowPtr window );
  71. void Terminate( void );
  72. void UnLoadTrafficLightLibrary();
  73. void LoadTrafficLightLibrary();
  74. void Initialize( void );
  75. void ForceEnvirons( void );
  76. Boolean IsAppWindow( WindowPtr window );
  77. Boolean IsDAWindow( WindowPtr window );
  78. Boolean TrapAvailable( short tNumber, TrapType tType );
  79. void AlertUser( void );
  80.  
  81. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  82.    dependency on the ordering of fields within a Rect */
  83.  
  84. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  85. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  86.  
  87.  
  88. /*————————————————————————————————————————————————————————————————————————————————————
  89.     _DataInit
  90.  
  91.     This routine is part of the MPW runtime library. This external reference to 
  92.     it is done so that we can unload its segment, %A5Init.
  93.  
  94. ————————————————————————————————————————————————————————————————————————————————————*/
  95.  
  96. extern void _DataInit();
  97.  
  98. /*————————————————————————————————————————————————————————————————————————————————————
  99.     main
  100. ————————————————————————————————————————————————————————————————————————————————————*/
  101.  
  102. #pragma segment Main
  103. main()
  104. {
  105.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  106.         
  107.     /*    If you have stack requirements that differ from the default,
  108.         then you could use SetApplLimit to increase StackSpace at 
  109.         this point, before calling MaxApplZone. */
  110.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  111.  
  112.     Initialize();                    /* initialize the program */
  113.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  114.         
  115.     EventLoop();                    /* call the main event loop */
  116. }
  117.  
  118.  
  119. /*————————————————————————————————————————————————————————————————————————————————————
  120.     EventLoop
  121.  
  122.     Get events forever, and handle them by calling DoEvent.
  123.     Get the events by calling WaitNextEvent, if it's available, otherwise
  124.     by calling GetNextEvent. Also call AdjustCursor each time through the loop.
  125.  
  126. ————————————————————————————————————————————————————————————————————————————————————*/
  127.  
  128. #pragma segment Main
  129. void EventLoop()
  130. {
  131.     RgnHandle    cursorRgn;
  132.     Boolean        gotEvent;
  133.     EventRecord    event;
  134.     Point        mouse;
  135.  
  136.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  137.     do {
  138.         /* use WNE if it is available */
  139.         if ( gHasWaitNextEvent ) {
  140.             GetGlobalMouse(&mouse);
  141.             AdjustCursor(mouse, cursorRgn);
  142.             gotEvent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursorRgn);
  143.         }
  144.         else {
  145.             SystemTask();
  146.             gotEvent = GetNextEvent(everyEvent, &event);
  147.         }
  148.         if ( gotEvent ) {
  149.             /* make sure we have the right cursor before handling the event */
  150.             AdjustCursor(event.where, cursorRgn);
  151.             DoEvent(&event);
  152.         }
  153.         /*    If you are using modeless dialogs that have editText items,
  154.             you will want to call IsDialogEvent to give the caret a chance
  155.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  156.             for a non-NIL value before calling IsDialogEvent. */
  157.     } while ( true );    /* loop forever; we quit via ExitToShell */
  158. } /*EventLoop*/
  159.  
  160.  
  161. /*————————————————————————————————————————————————————————————————————————————————————
  162.     DoEvent
  163.  
  164.     Do the right thing for an event. Determine what kind of event it is, and call
  165.     the appropriate routines.
  166.  
  167. ————————————————————————————————————————————————————————————————————————————————————*/
  168.  
  169. #pragma segment Main
  170.  
  171. void DoEvent( EventRecord *event)
  172. {
  173.     short        part, err;
  174.     WindowPtr    window;
  175.     Boolean        hit;
  176.     char        key;
  177.     Point        aPoint;
  178.  
  179.     switch ( event->what ) {
  180.         case mouseDown:
  181.             part = FindWindow(event->where, &window);
  182.             switch ( part ) {
  183.                 case inMenuBar:                /* process a mouse menu command (if any) */
  184.                     AdjustMenus();
  185.                     DoMenuCommand(MenuSelect(event->where));
  186.                     break;
  187.                 case inSysWindow:            /* let the system handle the mouseDown */
  188.                     SystemClick(event, window);
  189.                     break;
  190.                 case inContent:
  191.                     if ( window != FrontWindow() ) {
  192.                         SelectWindow(window);
  193.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  194.                     } else
  195.                         DoContentClick(window);
  196.                     break;
  197.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  198.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  199.                     break;
  200.                 case inGrow:
  201.                     break;
  202.                 case inZoomIn:
  203.                 case inZoomOut:
  204.                     hit = TrackBox(window, event->where, part);
  205.                     if ( hit ) {
  206.                         SetPort(window);                /* the window must be the current port... */
  207.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  208.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  209.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  210.                     }
  211.                     break;
  212.             }
  213.             break;
  214.         case keyDown:
  215.         case autoKey:                        /* check for menukey equivalents */
  216.             key = (char)(event->message & charCodeMask);
  217.             if ( event->modifiers & cmdKey )            /* Command key down */
  218.                 if ( event->what == keyDown ) {
  219.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  220.                     DoMenuCommand(MenuKey(key));
  221.                 }
  222.             break;
  223.         case activateEvt:
  224.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  225.             break;
  226.         case updateEvt:
  227.             DoUpdate((WindowPtr) event->message);
  228.             break;
  229.         /*  It is not a bad idea to at least call DIBadMount in response
  230.             to a diskEvt, so that the user can format a floppy. */
  231.         case diskEvt:
  232.             if ( HighWord(event->message) != noErr ) {
  233.                 SetPt(&aPoint, kDILeft, kDITop);
  234.                 err = DIBadMount(aPoint, event->message);
  235.             }
  236.             break;
  237.         case kOSEvent:
  238.         /*  must BitAND with 0x0FF to get only low byte */
  239.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  240.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  241.                     gInBackground = (event->message & kResumeMask) == 0;
  242.                     DoActivate(FrontWindow(), !gInBackground);
  243.                     break;
  244.             }
  245.             break;
  246.     }
  247. } /*DoEvent*/
  248.  
  249.  
  250. /*————————————————————————————————————————————————————————————————————————————————————
  251.     AdjustCursor
  252.  
  253.     Change the cursor's shape, depending on its position. This also calculates the region
  254.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  255.     that region, an event would be generated, causing this routine to be called,
  256.     allowing us to change the region to the region the mouse is currently in. If
  257.     there is more to the event than just “the mouse moved”, we get called before the
  258.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  259.     this is called again before we     fall back into WNE.
  260.  
  261. ————————————————————————————————————————————————————————————————————————————————————*/
  262.  
  263. #pragma segment Main
  264. void AdjustCursor( Point mouse, RgnHandle region )
  265. {
  266.     WindowPtr    window;
  267.     RgnHandle    arrowRgn;
  268.     RgnHandle    plusRgn;
  269.     Rect        globalPortRect;
  270.  
  271.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  272.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  273.         /* calculate regions for different cursor shapes */
  274.         arrowRgn = NewRgn();
  275.         plusRgn = NewRgn();
  276.  
  277.         /* start with a big, big rectangular region */
  278.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  279.  
  280.         /* calculate plusRgn */
  281.         if ( IsAppWindow(window) ) {
  282.             SetPort(window);    /* make a global version of the viewRect */
  283.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  284.             globalPortRect = window->portRect;
  285.             RectRgn(plusRgn, &globalPortRect);
  286.             SectRgn(plusRgn, window->visRgn, plusRgn);
  287.             SetOrigin(0, 0);
  288.         }
  289.  
  290.         /* subtract other regions from arrowRgn */
  291.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  292.  
  293.         /* change the cursor and the region parameter */
  294.         if ( PtInRgn(mouse, plusRgn) ) {
  295.             SetCursor(*GetCursor(plusCursor));
  296.             CopyRgn(plusRgn, region);
  297.         } else {
  298.             SetCursor(&qd.arrow);
  299.             CopyRgn(arrowRgn, region);
  300.         }
  301.  
  302.         /* get rid of our local regions */
  303.         DisposeRgn(arrowRgn);
  304.         DisposeRgn(plusRgn);
  305.     }
  306. } /*AdjustCursor*/
  307.  
  308. /*————————————————————————————————————————————————————————————————————————————————————
  309.     GetGlobalMouse
  310.  
  311.     Get the global coordinates of the mouse. When you call OSEventAvail
  312.     it will return either a pending event or a null event. In either case,
  313.     the where field of the event record will contain the current position
  314.     of the mouse in global coordinates and the modifiers field will reflect
  315.     the current state of the modifiers. Another way to get the global
  316.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  317.     being sure that thePort is set to a valid port.
  318.  
  319. ————————————————————————————————————————————————————————————————————————————————————*/
  320.  
  321. #pragma segment Main
  322. void GetGlobalMouse(Point    *mouse)
  323. {
  324.     EventRecord    event;
  325.     
  326.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  327.     *mouse = event.where;                /* just the mouse position */
  328. } /*GetGlobalMouse*/
  329.  
  330.  
  331. /*————————————————————————————————————————————————————————————————————————————————————
  332.     DoUpdate
  333.         
  334.     This is called when an update event is received for a window.
  335.     It calls DrawWindow to draw the contents of an application window.
  336.     As an effeciency measure that does not have to be followed, it
  337.     calls the drawing routine only if the visRgn is non-empty. This
  338.     will handle situations where calculations for drawing or drawing
  339.     itself is very time-consuming.
  340.  
  341. ————————————————————————————————————————————————————————————————————————————————————*/
  342.  
  343. #pragma segment Main
  344. void DoUpdate( WindowPtr window)
  345. {
  346.     if ( IsAppWindow(window) ) {
  347.         BeginUpdate(window);                /* this sets up the visRgn */
  348.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  349.             DrawWindow(window);
  350.         EndUpdate(window);
  351.     }
  352. } /*DoUpdate*/
  353.  
  354. /*————————————————————————————————————————————————————————————————————————————————————
  355.     DoActivate
  356.     
  357.     This is called when a window is activated or deactivated.
  358.     In Sample, the Window Manager's handling of activate and
  359.     deactivate events is sufficient. Other applications may have
  360.     TextEdit records, controls, lists, etc., to activate/deactivate. 
  361.  
  362. ————————————————————————————————————————————————————————————————————————————————————*/
  363.  
  364. #pragma segment Main
  365. void DoActivate(WindowPtr window, Boolean becomingActive)
  366. {
  367.     if ( IsAppWindow(window) ) {
  368.         if ( becomingActive )
  369.             /* do whatever you need to at activation */ ;
  370.         else
  371.             /* do whatever you need to at deactivation */ ;
  372.     }
  373. } /*DoActivate*/
  374.  
  375.  
  376. /*————————————————————————————————————————————————————————————————————————————————————
  377.     DoContentClick
  378.  
  379.     This is called when a mouse-down event occurs in the content of a window.
  380.     Other applications might want to call FindControl, TEClick, etc., to
  381.     further process the click.
  382.  
  383. ————————————————————————————————————————————————————————————————————————————————————*/
  384.  
  385. #pragma segment Main
  386.  
  387. void DoContentClick ( WindowPtr window )
  388.     #pragma unused( window )
  389.     
  390.     /* Here we are going to toggle the traffic light by getting the previous state 
  391.        and inverting it to new state. All the calls are going through v-table */
  392.       
  393.     SetLightState( !GetLightState() );
  394.     
  395. } /*DoContentClick*/
  396.  
  397.  
  398. /*————————————————————————————————————————————————————————————————————————————————————
  399.     DrawWindow
  400.  
  401.     Draw the contents of the application window. We do some drawing in color, using
  402.       Classic QuickDraw's color capabilities. This will be black and white on old
  403.        machines, but color on color machines. At this point, the window’s visRgn
  404.        is set to allow drawing only where it needs to be done.
  405.  
  406. ————————————————————————————————————————————————————————————————————————————————————*/
  407.  
  408. #pragma segment Main
  409.  
  410. void DrawWindow(WindowPtr window)
  411.     #pragma unused( window )
  412.     
  413.     /* DrawLight draws the traffic light through FunctionSets */
  414.     
  415.     DrawLight();
  416.  
  417. } /*DrawWindow*/
  418.  
  419.  
  420. /*————————————————————————————————————————————————————————————————————————————————————
  421.     AdjustMenus
  422.     
  423.     Enable and disable menus based on the current state.
  424.     The user can only select enabled menu items. We set up all the menu items
  425.     before calling MenuSelect or MenuKey, since these are the only times that
  426.     a menu item can be selected. Note that MenuSelect is also the only time
  427.     the user will see menu items. This approach to deciding what enable/
  428.     disable state a menu item has the advantage of concentrating all
  429.     the decision-making in one routine, as opposed to being spread throughout
  430.     the application. Other application designs may take a different approach
  431.     that is just as valid.
  432.  
  433. ————————————————————————————————————————————————————————————————————————————————————*/
  434.  
  435. #pragma segment Main
  436. void AdjustMenus()
  437. {
  438.     MenuHandle    menu;
  439.  
  440.     WindowPtr window = FrontWindow();
  441.  
  442.     menu = GetMenuHandle(mFile);
  443.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  444.         EnableItem(menu, iClose);
  445.     else
  446.         DisableItem(menu, iClose);    /* but not our traffic light window */
  447.  
  448.     menu = GetMenuHandle(mEdit);
  449.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  450.         EnableItem(menu, iUndo);
  451.         EnableItem(menu, iCut);
  452.         EnableItem(menu, iCopy);
  453.         EnableItem(menu, iClear);
  454.         EnableItem(menu, iPaste);
  455.     } else {                        /* …but we don’t use it */
  456.         DisableItem(menu, iUndo);
  457.         DisableItem(menu, iCut);
  458.         DisableItem(menu, iCopy);
  459.         DisableItem(menu, iClear);
  460.         DisableItem(menu, iPaste);
  461.     }
  462.     
  463.     /* after adjusting the application's menus adjust the traffic light menus by
  464.        going through the v-table */
  465.      
  466.     AdjustTrafficLightMenus( IsAppWindow(window) );
  467.  
  468. } /* AdjustMenus */
  469.  
  470. /*————————————————————————————————————————————————————————————————————————————————————
  471.     DoMenuCommand
  472.     
  473.     This is called when an item is chosen from the menu bar (after calling
  474.     MenuSelect or MenuKey). It performs the right operation for each command.
  475.     It is good to have both the result of MenuSelect and MenuKey go to
  476.     one routine like this to keep everything organized. It checks to see if the 
  477.     menu hit where the Apple, File, or Edit if so it calls the local DoMenuCommand
  478.     else it must be our traffic light's menu, therefore traffic light menu command 
  479.     is being called.
  480.  
  481. ————————————————————————————————————————————————————————————————————————————————————*/
  482.  
  483. #pragma segment Main
  484. void DoMenuCommand(long menuResult)
  485. {
  486.     short        menuID;                /* the resource ID of the selected menu */
  487.     short        menuItem;            /* the item number of the selected menu */
  488.     short        itemHit;
  489.     Str255        daName;
  490.     short        daRefNum;
  491.     Boolean        handledByDA;
  492.  
  493.     /* Here we are going to get a pointer to our object TLibraryFile this is 
  494.        necessary for allocating our traffic light's resources */
  495.     
  496.     menuID = HighWord(menuResult);    /* use macros for efficiency to... */
  497.     menuItem = LowWord(menuResult);    /* get menu item number and menu number */
  498.  
  499.     switch ( menuID ) {
  500.         case mApple:
  501.             switch ( menuItem ) {
  502.                 case iAbout:        /* bring up alert for About */
  503.                     itemHit = Alert(rAboutAlert, nil);
  504.                     break;
  505.                 default:            /* all non-About items in this menu are DAs */
  506.                     /* type Str255 is an array in MPW 3 */
  507.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  508.                     daRefNum = OpenDeskAcc(daName);
  509.                     break;
  510.             }
  511.             break;
  512.         case mFile:
  513.             switch ( menuItem ) {
  514.                 case iClose:
  515.                     DoCloseWindow(FrontWindow());
  516.                     break;
  517.                 case iQuit:
  518.                     Terminate();
  519.                     break;
  520.             }
  521.             break;
  522.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  523.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing  */
  524.             break;
  525.         case mLight:                /* this must be our shared library resource */
  526.             /* since DoMenuCommand uses the traffic light's resources. */
  527.             DoTrafficLightMenuCommand( menuItem );     /* Do traffic light's menu command */
  528.             break;
  529.     }
  530.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  531. } /*DoMenuCommand*/
  532.  
  533. /*————————————————————————————————————————————————————————————————————————————————————
  534.     DoCloseWindow
  535.     
  536.     Close a window. This handles desk accessory and application windows. Note the
  537.     traffic library manager allocated the windowrecord for window, so disposing of
  538.     the WindowRecord should be left upon the traffic light library.
  539.     
  540. ————————————————————————————————————————————————————————————————————————————————————*/
  541.  
  542.  
  543. #pragma segment Main
  544. Boolean DoCloseWindow(WindowPtr window)
  545. {
  546.     if ( IsDAWindow(window) )
  547.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  548.     else if ( IsAppWindow(window) )
  549.         FreeTrafficLight();                /* done with trafficlight, deallocate */
  550.     return true;
  551. } /*DoCloseWindow*/
  552.  
  553. /*————————————————————————————————————————————————————————————————————————————————————
  554.     Terminate
  555.  
  556.     Cleanup the application and exits. Close all of the windows, and cleanup our 
  557.     library. We replace the ExitToShell by UnLoadTrafficLightLibrary so we get a 
  558.     chance to unload the library and cleanup the library manager.
  559.  
  560. ————————————————————————————————————————————————————————————————————————————————————*/
  561.  
  562. #pragma segment Main
  563. void Terminate()
  564. {
  565.     WindowPtr    aWindow;
  566.     Boolean        closed;
  567.     
  568.     closed = true;
  569.  
  570.     do {
  571.         aWindow = FrontWindow();            /* get the current front window */
  572.         if ( aWindow != nil )
  573.             closed = DoCloseWindow(aWindow);/* close this window */    
  574.     } while (closed && (aWindow != nil));
  575.  
  576.     if (closed)
  577.         UnLoadTrafficLightLibrary();        /* exit if no cancellation */
  578.  
  579. } /*Terminate*/
  580.  
  581.  
  582. /*————————————————————————————————————————————————————————————————————————————————————
  583.     UnLoadTrafficLightLibrary
  584.     
  585.     unload the traffic light object and free the memory allocated by our library
  586.  
  587. ————————————————————————————————————————————————————————————————————————————————————*/
  588.  
  589. void UnLoadTrafficLightLibrary()
  590. {
  591.     /*    A library loaded with LoadFunctionSet() is not
  592.         unloaded until all objects from the library
  593.         are deleted and an UnloadFunctionSet() call is 
  594.         made to balance each LoadFunctionSet() call */
  595.     UnloadFunctionSet(kTrafficLightFunctionSet);
  596.  
  597.     CleanupLibraryManager();                /* clean up the library manager we are done. */
  598.     ExitToShell();                            /* Hasta la Vista baby! */
  599. } /* UnLoadTrafficLightLibrary */
  600.  
  601. /*————————————————————————————————————————————————————————————————————————————————————
  602.     LoadTrafficLightLibrary
  603.     
  604.     load the traffic light library. This library automatically creates a window and
  605.     attach a traffic menu to our current menu.
  606.  
  607. ————————————————————————————————————————————————————————————————————————————————————*/
  608.  
  609. void LoadTrafficLightLibrary()
  610. {
  611.     /* always initilize the library manager before any Shared Library calls. This
  612.        creates a local instance of TLibraryManager for accessing our libraries. */
  613.  
  614.     if( InitLibraryManager( 0,                /* we don't need memory in our local pool */
  615.                             kCurrentZone,     /* use application zone = current zone */
  616.                             kNormalMemory    /* default memory type, no VM stuff */
  617.                           ) == kNoError ) {
  618.         
  619.         /* make sure the library is available before initializing trafficlight(via LoadFunctionSet) */
  620.         if( LoadFunctionSet(kTrafficLightFunctionSet, true ) == kNoError) {
  621.             if( NewTrafficLight() )            /* initialize our trafficlight shared library */
  622.                 AlertUser();
  623.         }
  624.         else
  625.             AlertUser();
  626.     }
  627.     else
  628.         AlertUser();                        /* not good. SLM IS NOT INSLALLED */
  629.  
  630. } /* LoadTrafficLightLibrary */
  631.  
  632. /*————————————————————————————————————————————————————————————————————————————————————
  633.     Initialize
  634.     
  635.     Set up the whole world, including global variables, Toolbox managers,
  636.     and menus. Sample is going to create its window, and traffic menu through its
  637.     traffic library, using the shared library manager(Nahhhh...). The Library auto-
  638.     matically create a window, attach a menu and draws the traffic light.
  639.  
  640. ————————————————————————————————————————————————————————————————————————————————————*/
  641.  
  642. #pragma segment Initialize
  643. void Initialize()
  644. {
  645.     Handle        menuBar;
  646.     long        total, contig;
  647.     EventRecord event;
  648.     short        count;
  649.  
  650.     gInBackground = false;
  651.  
  652.     InitGraf((Ptr) &qd.thePort);
  653.     InitFonts();
  654.     InitWindows();
  655.     InitMenus();
  656.     TEInit();
  657.     InitDialogs(nil);
  658.     InitCursor();
  659.          
  660.     /* This next bit of code is necessary to allow the default button of our
  661.        alert be outlined */
  662.  
  663.     for (count = 1; count <= 3; count++)
  664.         EventAvail(everyEvent, &event);
  665.          
  666.     /* Ignore the error returned from SysEnvirons; even if an error occurred,
  667.        the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  668.        call to SysEnvirons by calling it after initializing AppleTalk.*/
  669.  
  670.     SysEnvirons(kSysEnvironsVersion, &gMac);
  671.     
  672.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  673.     
  674.     if (gMac.machineType < 0) AlertUser();
  675.             
  676.     /* Move TrapAvailable call to after SysEnvirons so that we can tell
  677.        in TrapAvailable if a tool trap value is out of range. */
  678.  
  679.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  680.           
  681.     /* We used to make a check for memory at this point by examining ApplLimit,
  682.        ApplicationZone, and StackSpace and comparing that to the minimum size we told
  683.        MultiFinder we needed. This did not work well because it assumed too much about
  684.        the relationship between what we asked MultiFinder for and what we would actually
  685.        get back, as well as how to measure it. Instead, we will use an alternate
  686.        method comprised of two steps. */
  687.  
  688.     /* It is better to first check the size of the application heap against a value
  689.        that you have determined is the smallest heap the application can reasonably
  690.        work in. This number should be derived by examining the size of the heap that
  691.        is actually provided by MultiFinder when the minimum size requested is used.
  692.        The derivation of the minimum size requested from MultiFinder is described
  693.        in Sample.h. The check should be made because the preferred size can end up
  694.        being set smaller than the minimum size by the user. This extra check acts to
  695.        insure that your application is starting from a solid memory foundation. */
  696.  
  697.     if ((long) GetApplLimit() - (long) ApplicationZone() < kMinHeap) AlertUser();
  698.  
  699.     /* Next, make sure that enough memory is free for your application to run. It
  700.        is possible for a situation to arise where the heap may have been of required
  701.        size, but a large scrap was loaded which left too little memory. To check for
  702.        this, call PurgeSpace and compare the result with a value that you have determined
  703.        is the minimum amount of free memory your application needs at initialization.
  704.        This number can be derived several different ways. One way that is fairly
  705.        straightforward is to run the application in the minimum size configuration
  706.        as described previously. Call PurgeSpace at initialization and examine the value
  707.        returned. However, you should make sure that this result is not being modified
  708.        by the scrap's presence. You can do that by calling ZeroScrap before calling
  709.        PurgeSpace. Make sure to remove that call before shipping, though.*/
  710.         
  711.     PurgeSpace(&total, &contig);
  712.     if (total < kMinSpace) AlertUser();
  713.  
  714.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  715.     if ( menuBar == nil ) AlertUser();
  716.     SetMenuBar(menuBar);                    /* install menus */
  717.     DisposeHandle(menuBar);
  718.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  719.  
  720.     DrawMenuBar();                            /* go ahead and update the menu bar */
  721.  
  722.     LoadTrafficLightLibrary();                /* Load trafficlight shared library */
  723.     
  724. } /*Initialize*/
  725.  
  726. /*————————————————————————————————————————————————————————————————————————————————————
  727.     IsAppWindow
  728.     
  729.     Check to see if a window belongs to the application. If the window pointer
  730.     passed was NIL, then it could not be an application window. WindowKinds
  731.     that are negative belong to the system and windowKinds less than userKind
  732.     are reserved by Apple except for windowKinds equal to dialogKind, which
  733.     mean it is a dialog.
  734.  
  735. ————————————————————————————————————————————————————————————————————————————————————*/
  736.  
  737. #pragma segment Main
  738. Boolean IsAppWindow( WindowPtr window)
  739. {
  740.     short        windowKind;
  741.  
  742.     if ( window == nil )
  743.         return false;
  744.     else {    /* application windows have windowKinds = userKind (8) */
  745.         windowKind = ((WindowPeek) window)->windowKind;
  746.         return ( windowKind == userKind );
  747.     }
  748. } /*IsAppWindow*/
  749.  
  750. /*————————————————————————————————————————————————————————————————————————————————————
  751.     IsDAWindow
  752.  
  753.     Check to see if a window belongs to a desk accessory
  754.  
  755. ————————————————————————————————————————————————————————————————————————————————————*/
  756.  
  757. #pragma segment Main
  758. Boolean IsDAWindow(WindowPtr window)
  759. {
  760.     if ( window == nil )
  761.         return false;
  762.     else    /* DA windows have negative windowKinds */
  763.         return ( ((WindowPeek) window)->windowKind < 0 );
  764. } /*IsDAWindow*/
  765.  
  766.  
  767. /*————————————————————————————————————————————————————————————————————————————————————
  768.     TrapAvailable
  769.  
  770.     Check to see if a given trap is implemented. This is only used by the
  771.     Initialize routine in this program, so we put it in the Initialize segment.
  772.     The recommended approach to see if a trap is implemented is to see if
  773.     the address of the trap routine is the same as the address of the
  774.     Unimplemented trap.
  775.  
  776. ————————————————————————————————————————————————————————————————————————————————————*/
  777.  
  778. #pragma segment Initialize
  779. Boolean TrapAvailable( short tNumber, TrapType tType)
  780. {
  781.     if ( ( tType == ToolTrap ) &&
  782.         ( gMac.machineType > envMachUnknown ) &&
  783.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  784.         tNumber = tNumber & 0x03FF;
  785.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  786.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  787.     }
  788.     return NGetTrapAddress(tNumber, tType) != NGetTrapAddress(_Unimplemented, tType);
  789. } /*TrapAvailable*/
  790.  
  791. /*————————————————————————————————————————————————————————————————————————————————————
  792.     AlertUser
  793.     
  794.     Display an alert that tells the user an error occurred, then exit the program.
  795.     This routine is used as an ultimate bail-out for serious errors that prohibit
  796.     the continuation of the application. Errors that do not require the termination
  797.     of the application should be handled in a different manner. Error checking and
  798.     reporting has a place even in the simplest application. The error number is used
  799.     to index an 'STR#' resource so that a relevant message can be displayed.
  800.  
  801. ————————————————————————————————————————————————————————————————————————————————————*/
  802.  
  803. #pragma segment Main
  804. void AlertUser()
  805. {
  806.     short        itemHit;
  807.  
  808.     SetCursor(&qd.arrow);
  809.     itemHit = Alert(rUserAlert, nil);
  810.     UnLoadTrafficLightLibrary();
  811. } /* AlertUser */